/*
 * @Description: 看图著录按钮
 * @Author: Rfan
 * @Date: 2023-02-25 10:27:14
 * @LastEditTime: 2023-02-27 11:51:55
 */

import { useMemo, useState } from 'react';
import { Button } from 'antd';
import classNames from 'classnames/bind';
import EditArchiveItem from '../dialogs/EditArchiveItem';
import { useLevelTableContext } from '../../contexts/LevelTableContext';
import Preview from '@/components/Preview';
import { fetchERecords, IDownLevelParams } from '@/api/archives/archives';
import { IPageQuery } from '@/interfaces/global';
import styles from '../../styles/descWithImg.module.scss';

const cx = classNames.bind(styles);

interface IDescWithImgProps {
  selectData: any;
}
const DescWithImg = (props: IDescWithImgProps) => {
  const { selectData } = props;
  const { baseInfo, selectItems } = useLevelTableContext();

  // 弹窗展示状态
  const [visible, setVisible] = useState(false);
  // 预览列表
  const [eLevelInfo, setELevelInfo] = useState(null);

  /**
   * @description: 文件级获取电子文件列表
   * @return {*}
   */
  const getELevelList = () => {
    const params: IPageQuery<IDownLevelParams> = {
      pageNo: 1,
      pageSize: 20,
      param: {
        commonParams: { dbName: 'data' },
        atCode: baseInfo.atCode,
        atType: baseInfo.atType,
        level: 0,
        downLevelId: selectData.row_id
      }
    };
    return new Promise((resolve) => {
      fetchERecords(params).then((res) => {
        const data = res.data;
        setELevelInfo(data.results);
        resolve(data.results);
      });
    });
  };

  const showDescriptionDialog = async () => {
    await getELevelList();
    setVisible(true);
  };

  return (
    <>
      <Button
        type="text"
        disabled={selectItems.length !== 1}
        onClick={() => {
          showDescriptionDialog();
        }}
      >
        看图著录
      </Button>

      {/* 预览弹窗 */}
      {eLevelInfo?.data?.length > 0 && (
        <Preview
          visible={visible}
          title=""
          data={null}
          list={eLevelInfo?.data || []}
          width="46%"
          style={{ right: '-23%' }}
          onClose={() => {
            setVisible(false);
          }}
          upper={eLevelInfo?.upLevel}
          fields={eLevelInfo?.fields || []}
          baseInfo={baseInfo}
        />
      )}

      {/* 编辑弹窗 */}
      {useMemo(
        () => (
          <EditArchiveItem
            visible={visible}
            data={selectData}
            title="看图著录"
            width="92%"
            style={{ margin: '0 0 0 8%' }}
            coordinate={{
              atCode: baseInfo.atCode,
              atType: baseInfo.atType,
              level: baseInfo.level
            }}
            mask={false}
            wrapClassName={cx('edit-modal-wrap')}
            onClose={() => {
              setVisible(false);
            }}
          />
        ),
        [visible]
      )}
    </>
  );
};

export default DescWithImg;
